#-*- coding: utf-8 -*-

"""
    PyJICK: Python Intelligent Control KIT
    Copyright (C) 2012  Jack Krieger
    This file is part of PyJICK.

    See the file LICENSE for copying permission.
"""

import os
import logging
import sleekxmpp
import pkg_resources

from settings import OptionManager
#from modules import ModuleManager
from pyjick import PyJICK

#import eggs



class Nest():

	"""
	PyJICK Nest (a SleekXMPP bot connector)
	"""

	def __init__(self, workspace, settings):
		
		self.settings = OptionManager(settings)

		# Setup logging.
		self.logger = logging.basicConfig(level=1, format='%(levelname)-8s %(message)s')



		jid = self.settings.option('ACCOUNT', 'jid')
		password = self.settings.option('ACCOUNT', 'password')

 		
		self.eggs = self.collect_eggs(os.path.join(workspace, 'modules'))

		# Init SleekXMPP client.
		self.xmpp = sleekxmpp.ClientXMPP(jid, password)

		self.rooms = [('pyjick@conference.jabber.ru', 'pyjick')]#, ('jjk@conference.jabber.ru', 'pyjick2'),]
		self.birds = []



	def build(self):


		# The session_start event will be triggered when
		# the bot establishes its connection with the server
		# and the XML streams are ready for use. We want to
		# listen for this event so that we we can initialize
		# our roster.
		self.xmpp.add_event_handler("session_start", self.start)

		# Setup the SleekXMPP client and register plugins. Note that while plugins may
		# have interdependencies, the order in which you register them does
		# not matter.
		self.xmpp.register_plugin('xep_0030') # Service Discovery
		self.xmpp.register_plugin('xep_0045') # Multi-User Chat
		self.xmpp.register_plugin('xep_0199') # XMPP Ping

		# Proxy support if enabled.
		proxy_server = self.settings.option('PROXY', 'server')
		proxy_port = self.settings.option('PROXY', 'port') or 3128
		proxy_login = self.settings.option('PROXY', 'login') or ''
		proxy_password = self.settings.option('PROXY', 'password') or ''

		if proxy_server:
			self.xmpp.use_proxy = True
			self.xmpp.proxy_config = {
				'host': proxy_server,
				'port': proxy_port,
				'username': proxy_login,
				'password': proxy_password
				}

		# Connect to the XMPP server and start processing XMPP stanzas.
		if self.xmpp.connect():
			# If you do not have the dnspython library installed, you will need
			# to manually specify the name of the server if it does not match
			# the one in the JID. For example, to use Google Talk you would
			# need to use:
			#
			# if xmpp.connect(('talk.google.com', 5222)):
			#     ...
			self.xmpp.process(block=True)
			print("Done")

		else:
			print("Unable to connect")


		


	def start(self, event):
		"""
		Process the session_start event.

		Typical actions for the session_start event are
		requesting the roster and broadcasting an initial
		presence stanza.

		Arguments:
			event -- An empty dictionary. The session_start
					 event does not provide any additional
					 data.
		"""

		#self.xmpp.get_roster()
		self.xmpp.send_presence()

		print 'birds, fly!'

		for (room, nick) in self.rooms:
			bird = PyJICK(self, room, nick)
			self.birds.append(bird)

			# The groupchat_presence event is triggered whenever a
			# presence stanza is received from any chat room, including
			# any presences you send yourself. To limit event handling
			# to a single room, use the events muc::room@server::presence,
			# muc::room@server::got_online, or muc::room@server::got_offline.
			self.xmpp.add_event_handler("muc::%s::got_online" % room, bird.on_online)
			self.xmpp.add_event_handler("muc::%s::presence" % room, bird.on_presence)
			self.xmpp.add_event_handler("muc::%s::got_offline" % room, bird.on_offline)

			# The groupchat_message event is triggered whenever a message
			# stanza is received from any chat room. If you also also
			# register a handler for the 'message' event, MUC messages
			# will be processed by both handlers.
			self.xmpp.add_event_handler("muc::%s::message" % room, bird.on_message)

			# If a room password is needed, use: password=the_room_password,
			self.xmpp.plugin['xep_0045'].joinMUC(room, nick, wait=True)



	def stop(self, event):
		pass



	def collect_eggs(self, workspace):
		#print workspace

		workingset = pkg_resources.WorkingSet((workspace,))
		environment = pkg_resources.Environment(search_path=[workspace,])

		eggs, errors = workingset.find_plugins(environment)
			
		# тут можно будет глобально отключать плагины
		map(workingset.add, eggs)
		
		for egg in workingset:
			egg.activate()

			print pkg_resources.iter_entry_points(egg)
			print pkg_resources.get_entry_map(egg)

		return workingset
